<template>
  <div v-if="editAuth">
    <page-header
      :title="$route.query.id ? $t('m.Edit_store') : $t('m.create_store')"
      is-emphasize
    >
      <el-button @click="saveClick()">{{
        $route.query.id ? $t('m.save') : $t('m.branch_Create')
      }}</el-button>
    </page-header>
    <div class="detail_div container">
      <div class="detail_left">
        <div class="detail_left_div" style="padding-bottom: 20px">
          <el-form
            label-position="top"
            :model="params"
            :rules="paramsRule"
            ref="params1"
          >
            <div class="create_title">
              {{ $t('m.branch_Merchant_Information') }}
            </div>
            <div class="create_title2">
              {{ $t('m.Shop_Created_shop_logo') }}*
            </div>
            <el-form-item style="margin-bottom: 33px" prop="logo">
              <el-checkbox-group
                v-model="params.logo"
                v-show="false"
              ></el-checkbox-group>
              <div class="logo_img" v-show="params.logo">
                <el-image
                  class="logo_img"
                  fit="cover"
                  :src="fileUrlFormat(params.logo)"
                  :preview-src-list="[fileUrlFormat(params.logo)]"
                >
                </el-image>
                <img
                  src="@/assets/imgs/ic_del@2x.png"
                  alt=""
                  @click="deleteLogo()"
                  class="delImg"
                />
              </div>
              <el-upload
                :data="{ type: 1 }"
                :show-file-list="false"
                action="/manage/common/files/upload"
                :before-upload="beforeUpload"
                :on-success="getLogo"
                name="files"
                :limit="1"
                :file-list="fileList1"
                accept="image/jpeg,image/png"
                class="logo_img"
                v-show="!params.logo"
              >
                <img
                  src="@/assets/imgs/appphoto@2x.png"
                  alt=""
                  class="logo_img"
                />
              </el-upload>
            </el-form-item>
            <div class="create_title2">
              {{ $t('m.Shop_Created_shop_images') }}
            </div>
            <div class="detail_text" style="display: flex">
              <div
                v-for="(item, index) in fileList2"
                :key="index"
                class="shop_img"
              >
                <el-image
                  class="shop_img"
                  fit="cover"
                  :src="fileUrlFormat(item.url)"
                  :preview-src-list="[fileUrlFormat(item.url)]"
                >
                </el-image>
                <img
                  src="@/assets/imgs/ic_del@2x.png"
                  alt=""
                  @click="deletePicture(index)"
                  class="delImg"
                />
              </div>
              <el-upload
                :data="{ type: 1 }"
                :show-file-list="false"
                action="/manage/common/files/upload"
                name="files"
                :on-success="getPicture"
                :before-upload="beforeUpload"
                :limit="5"
                list-type="picture"
                :file-list="fileList2"
                accept="image/jpeg,image/png"
                class="shop_img"
                v-show="fileList2.length != 5"
              >
                <img
                  src="@/assets/imgs/appphoto@2x.png"
                  alt=""
                  class="shop_img"
                />
              </el-upload>
            </div>
            <div class="create_title2">{{ $t('m.Shop_name') }}*</div>
            <el-form-item prop="shopName">
              <el-input
                v-model="params.shopName"
                :placeholder="$t('m.Please_enter')"
                clearable
                maxlength="50"
              ></el-input>
            </el-form-item>
            <div class="create_title2">{{ $t('m.Merchant_type') }}*</div>
            <el-form-item prop="industryId">
              <el-select
                v-model="params.industryId"
                :placeholder="$t('m.pleaseChoose')"
                style="width: 100%"
              >
                <el-option
                  v-for="item in industrys"
                  :key="item.id"
                  :label="
                    item.description
                      ? item.industryName + ' (' + item.description + ')'
                      : item.industryName
                  "
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <div class="create_title2">{{ $t('m.Shop_Details_Address') }}*</div>
            <el-form-item prop="address">
              <el-input
                v-model="params.address"
                :placeholder="$t('m.Please_enter')"
                maxlength="200"
                clearable
              ></el-input>
            </el-form-item>
            <div class="create_title2">{{ $t('m.Location_pin') }}*</div>
            <el-form-item prop="addressMap">
              <el-input
                style="width: 100%"
                v-model="params.addressMap"
                @blur="searchMap()"
                @keyup.enter.native="searchMap()"
                clearable
                :placeholder="$t('m.pleaseChoose')"
              ></el-input>
            </el-form-item>
            <div style="height: 280px; width: 100%; margin-bottom: 20px">
              <div
                id="googleMap"
                style="
                  height: 280px;
                  width: 100%;
                  border: 1px solid #d2d8e2;
                  border-radius: 4px;
                "
              ></div>
            </div>

            <div class="create_title">{{ $t('m.Contact_person_msg') }}</div>
            <div class="create_title2">{{ $t('m.Contact_person') }}*</div>
            <el-form-item prop="principal">
              <el-input
                v-model="params.principal"
                :placeholder="$t('m.Please_enter')"
                maxlength="15"
                clearable
              ></el-input>
            </el-form-item>
            <div class="create_title2">{{ $t('m.Shop_Details_Contact') }}*</div>
            <el-form-item prop="phone">
              <div class="flex_div">
                <el-select
                  v-model="params.code"
                  :placeholder="$t('m.pleaseChoose')"
                  style="width: 150px; margin-right: 12px"
                  filterable
                >
                  <el-option
                    v-for="(item, index) in countryCode"
                    :key="index"
                    :label="'+' + item.codes"
                    :value="Number(item.codes)"
                  >
                  </el-option>
                </el-select>
                <el-input
                  clearable
                  v-model="params.phone"
                  :placeholder="$t('m.Please_enter')"
                  @input="changePhone"
                  maxlength="15"
                  minlength="8"
                />
              </div>
            </el-form-item>
            <div class="create_title">{{ $t('m.Billing_information') }}</div>
            <div class="create_title2">
              {{ $t('m.Franchisee_belong') }}
              <span>*</span>
            </div>
            <el-form-item prop="agentId">
              <el-cascader
                :placeholder="$t('m.pleaseChoose')"
                style="width: 100%"
                :disabled="$route.query.id || getAgentLevel() == 2 ? true : false"
                v-model="params.agentId"
                :options="agents"
                :props="{
                  checkStrictly: true,
                  emitPath: false,
                  value: 'id',
                  label: 'name'
                }"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
            <div class="create_title2">
              {{ $t('m.Shop_Details_Profit_allocation') }}(%)*
            </div>
            <el-form-item prop="ratio">
              <el-input
                v-model="params.ratio"
                :placeholder="$t('m.Please_enter')"
                @input="changeRatio"
                maxlength="3"
                clearable
                ><template slot="append">%</template></el-input
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="detail_right">
        <div class="detail_left_div" style="padding-bottom: 20px">
          <div class="create_title">{{ $t('m.branch_Operation_hours') }}</div>
          <el-radio-group v-model="params.openTimeType">
            <el-radio :label="1"
              ><span style="font-size: 16px">{{
                $t('m.Time_period_preset')
              }}</span></el-radio
            >
            <el-radio :label="2"
              ><span style="font-size: 16px">{{
                $t('m.Daily_customization')
              }}</span></el-radio
            >
          </el-radio-group>
          <div v-show="params.openTimeType == 1" class="tiem_el_checkbox">
            <el-checkbox-group v-model="checkedCities">
              <el-checkbox
                v-for="item in cities"
                :label="item.value"
                :key="item.value"
                >{{ item.label }}</el-checkbox
              >
            </el-checkbox-group>
          </div>
          <div class="shop_time" v-show="params.openTimeType == 1">
            <div class="time_check" style="padding: 6px 0 0">
              <div class="shop_week">
                <div class="week_name">{{ timeList1.names }}</div>
                <el-switch
                  v-model="timeList1.allDay"
                  active-color="var(--text-color)"
                  inactive-color="#d2d8e2"
                  @change="changeCheck()"
                >
                </el-switch>
              </div>
            </div>
            <div class="shop_div2">
              <el-time-picker
                v-show="timeList1.stage > 0"
                is-range
                :editable="false"
                v-model="timeList1.rangeTime1"
                :disabled="timeList1.disabledTime"
                range-separator="-"
                :picker-options="{
                  selectableRange: '00:00:00 - 23:59:59'
                }"
                format="HH:mm"
                value-format="HH:mm"
                :start-placeholder="$t('m.TimePicker_StartDate')"
                :end-placeholder="$t('m.TimePicker_EndDate')"
                :placeholder="$t('m.branch_Please_time')"
              >
              </el-time-picker>
              <el-time-picker
                is-range
                :editable="false"
                v-show="timeList1.stage > 1"
                v-model="timeList1.rangeTime2"
                :disabled="timeList1.disabledTime"
                range-separator="-"
                :picker-options="{
                  selectableRange: '00:00:00 - 23:59:59'
                }"
                format="HH:mm"
                value-format="HH:mm"
                :start-placeholder="$t('m.TimePicker_StartDate')"
                :end-placeholder="$t('m.TimePicker_EndDate')"
                :placeholder="$t('m.branch_Please_time')"
              >
              </el-time-picker>
              <el-time-picker
                v-show="timeList1.stage > 2"
                is-range
                :editable="false"
                v-model="timeList1.rangeTime3"
                :disabled="timeList1.disabledTime"
                range-separator="-"
                :picker-options="{
                  selectableRange: '00:00:00 - 23:59:59'
                }"
                format="HH:mm"
                value-format="HH:mm"
                :start-placeholder="$t('m.TimePicker_StartDate')"
                :end-placeholder="$t('m.TimePicker_EndDate')"
                :placeholder="$t('m.branch_Please_time')"
              >
              </el-time-picker>
              <el-time-picker
                v-show="timeList1.stage > 3"
                is-range
                :editable="false"
                v-model="timeList1.rangeTime4"
                :disabled="timeList1.disabledTime"
                range-separator="-"
                :picker-options="{
                  selectableRange: '00:00:00 - 23:59:59'
                }"
                format="HH:mm"
                value-format="HH:mm"
                :start-placeholder="$t('m.TimePicker_StartDate')"
                :end-placeholder="$t('m.TimePicker_EndDate')"
                :placeholder="$t('m.branch_Please_time')"
              >
              </el-time-picker>
              <div>
                <i
                  class="el-icon-minus shop_plus1 shop_plus"
                  :class="{ shop_icon: timeList1.stage > 1 }"
                  v-show="timeList1.allDay && timeList1.stage > 1"
                ></i>
                <i
                  class="el-icon-minus shop_plus"
                  :class="{ shop_icon: timeList1.stage > 1 }"
                  @click="reduceTime1()"
                  v-show="!timeList1.allDay && timeList1.stage > 1"
                ></i>
                <i
                  class="el-icon-plus shop_plus1 shop_plus"
                  :class="{
                    shop_icon: timeList1.stage > 1,
                    shop_icon2: timeList1.stage > 1
                  }"
                  v-show="timeList1.allDay || timeList1.stage == 4"
                ></i>
                <i
                  class="el-icon-plus shop_plus"
                  :class="{
                    shop_icon: timeList1.stage > 1,
                    shop_icon2: timeList1.stage > 1
                  }"
                  @click="addTime1()"
                  v-show="!timeList1.allDay && timeList1.stage < 4"
                ></i>
              </div>
            </div>
          </div>
          <div
            class="shop_time"
            v-for="(item, index) in timeList"
            :key="index"
            v-show="params.openTimeType == 2"
          >
            <div class="time_check">
              <div class="shop_week">
                <div class="week_name">{{ item.name }}</div>
                <el-switch
                  v-model="item.check2"
                  active-color="var(--text-color)"
                  inactive-color="#d2d8e2"
                  @change="changeCheck1(item, index)"
                >
                </el-switch>
              </div>
              <div
                v-show="item.check2"
                class="shop_week"
                style="margin-left: 42px"
              >
                <div class="week_name">{{ item.names }}</div>
                <el-switch
                  v-show="item.check2"
                  v-model="item.allDay"
                  active-color="var(--text-color)"
                  inactive-color="#d2d8e2"
                  @change="changeCheck2(item, index)"
                >
                </el-switch>
              </div>
            </div>
            <div class="shop_div2">
              <el-time-picker
                v-show="item.check2 && item.stage > 0"
                is-range
                :editable="false"
                v-model="item.rangeTime1"
                :disabled="item.disabledTime"
                range-separator="-"
                :picker-options="{
                  selectableRange: '00:00:00 - 23:59:59'
                }"
                format="HH:mm"
                value-format="HH:mm"
                :start-placeholder="$t('m.TimePicker_StartDate')"
                :end-placeholder="$t('m.TimePicker_EndDate')"
                :placeholder="$t('m.branch_Please_time')"
              >
              </el-time-picker>
              <el-time-picker
                is-range
                :editable="false"
                v-show="item.check2 && item.stage > 1"
                v-model="item.rangeTime2"
                :disabled="item.disabledTime"
                range-separator="-"
                :picker-options="{
                  selectableRange: '00:00:00 - 23:59:59'
                }"
                format="HH:mm"
                value-format="HH:mm"
                :start-placeholder="$t('m.TimePicker_StartDate')"
                :end-placeholder="$t('m.TimePicker_EndDate')"
                :placeholder="$t('m.branch_Please_time')"
              >
              </el-time-picker>
              <el-time-picker
                v-show="item.check2 && item.stage > 2"
                is-range
                :editable="false"
                v-model="item.rangeTime3"
                :disabled="item.disabledTime"
                range-separator="-"
                :picker-options="{
                  selectableRange: '00:00:00 - 23:59:59'
                }"
                format="HH:mm"
                value-format="HH:mm"
                :start-placeholder="$t('m.TimePicker_StartDate')"
                :end-placeholder="$t('m.TimePicker_EndDate')"
                :placeholder="$t('m.branch_Please_time')"
              >
              </el-time-picker>
              <el-time-picker
                v-show="item.check2 && item.stage > 3"
                is-range
                :editable="false"
                v-model="item.rangeTime4"
                :disabled="item.disabledTime"
                range-separator="-"
                :picker-options="{
                  selectableRange: '00:00:00 - 23:59:59'
                }"
                format="HH:mm"
                value-format="HH:mm"
                :start-placeholder="$t('m.TimePicker_StartDate')"
                :end-placeholder="$t('m.TimePicker_EndDate')"
                :placeholder="$t('m.branch_Please_time')"
              >
              </el-time-picker>
              <div>
                <i
                  class="el-icon-minus shop_plus1 shop_plus"
                  :class="{ shop_icon: item.stage > 1 }"
                  v-show="item.allDay && item.stage > 1"
                ></i>
                <i
                  class="el-icon-minus shop_plus"
                  :class="{ shop_icon: item.stage > 1 }"
                  @click="reduceTime(index)"
                  v-show="!item.allDay && item.check2 && item.stage > 1"
                ></i>
                <i
                  class="el-icon-plus shop_plus1 shop_plus"
                  :class="{
                    shop_icon: item.stage > 1,
                    shop_icon2: item.stage > 1
                  }"
                  v-show="item.allDay || item.stage == 4"
                ></i>
                <i
                  class="el-icon-plus shop_plus"
                  :class="{
                    shop_icon: item.stage > 1,
                    shop_icon2: item.stage > 1
                  }"
                  @click="addTime(index)"
                  v-show="!item.allDay && item.check2 && item.stage < 4"
                ></i>
              </div>
            </div>
          </div>
        </div>

        <div
          class="detail_left_div detail_left_div2"
          style="padding-bottom: 20px"
        >
          <div class="create_title">
            {{ $t('m.branch_branch_Assign_station') }}
          </div>
          <el-transfer
            filterable
            :filter-placeholder="$t('m.Station_SN')"
            v-model="params.scanList"
            :titles="[$t('m.Station_list'), $t('m.Station_assigned')]"
            :data="stations"
            :render-content="renderContent"
          >
          </el-transfer>
        </div>
      </div>
    </div>

    <!-- 邀请店主-->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="inviteDialog"
      :title="$t('m.Invite_merchant_owner')"
      width="520px"
      top="200px"
      append-to-body
      @close="backPage"
    >
 
      <div class="dialog_content el_input_disabled" v-if="linkType == 1">
        <div class="dialog_content1">
          {{ $t('m.Choose_oneWay_invite_merchant') }}
        </div>
        <el-radio-group v-model="elRadio" style="margin-bottom: 12px">
          <el-radio :label="1">{{
            $t('m.Invite_by_Invitation_link')
          }}</el-radio>
          <el-radio :label="2">{{ $t('m.Invite_by_email') }}</el-radio>
        </el-radio-group>
        <div class="dialog_content3">
          <el-input
            v-show="elRadio == 1"
            style="width: 100%"
            disabled
            :value="inviteData.inviteUrl"
            ><template slot="append"
              ><div @click="$util.copyText(inviteData.inviteUrl)">
                {{ $t('m.Copy') }}
              </div></template
            ></el-input
          >
          <el-form
            style="width: 100%"
            v-if="elRadio == 2"
            :model="ruleForms"
            :rules="rules"
            ref="ruleForms"
          >
            <el-form-item prop="email" key="email">
              <el-input
                v-model="ruleForms.email"
                maxlength="320"
                style="width: 100%"
                :placeholder="$t('m.Please_enter')"
                clearable
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div
          class="dialog_content2"
          v-show="elRadio == 1"
          style="margin-top: 12px"
        >
          {{
            $t('m.Expire_in_fourteen')
              .replace('$times', inviteData.remainDays)
              .replace(
                '$days',
                inviteData.remainDays > 1 ? $t('m.days') : $t('m.day')
              )
          }}
        </div>
      </div>
      <div class="dialog_content" v-else>
        <div class="dialog_content1">
          {{ $t('m.Merchant_successfully_created') }}
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="cancel_btn" v-if="linkType == 2" @click="backPage">{{
          $t('m.Later')
        }}</el-button>
        <el-button @click="submitInvite" class="cancel_btn confirm_btn">{{
          linkType == 2 ? $t('m.Invite_now') : $t('m.confirm_')
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import countries from '@/common/json/countries.json'
export default {
  data () {
    return {
      params: {
        address: '', //	详细地址信息
        addressMap: '', //	地址信息(地图搜索的地址)
        agentId: '', //	代理id
        billingId: '', //	计费规则id
        branchProfile: {
          de: '',
          en: '',
          fr: '',
          vi: '',
          vi: '',
          zh: ''
        },
        code: this.$country.codes, //	国家码
        depositId: '', //	押金规则id
        id: '', //	id
        images: '', //	网点形象照片地址
        industryId: '', //	行业id
        lat: 38.9958641, // 纬度
        lng: -76.909393, // 经度
        logo: '', //	logo图片地址
        openTime: {
          businessHours: [],
          check: true
        }, //	营业时间(json)
        openTimeType: 1, // 营业时间类型：1.时间段预设 2.自定义
        phone: '', //	电话
        principal: '', //	负责人
        ratio: '', //	分成比例 0-100
        scanList: [], //	机柜扫码标号
        shopName: '' //	网点名称
      },
      paramsRule: {
        logo: [
          {
            required: true,
            trigger: 'change',
            message: this.$t('m.Please_upload_logo')
          }
        ],
        shopName: [
          {
            required: true,
            message: this.$t('m.Shop_Created_shop'),
            trigger: 'blur'
          }
        ],
        industryId: [
          {
            required: true,
            message: this.$t('m.Select_merchant_type'),
            trigger: 'change'
          }
        ],
        phone: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('m.Enterphonenumber2')
          }
        ],
        principal: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('m.Enter_principal')
          }
        ],
        agentId: [
          {
            required: true,
            message: this.$t('m.Station_Selecttheagent'),
            trigger: 'change'
          }
        ],
        billingId: [
          {
            required: true,
            message: this.$t('m.Select_Pricing_Plan'),
            trigger: 'change'
          }
        ],
        // depositId: [
        //   {
        //     required: true,
        //     message: this.$t('m.Please_select_deposit'),
        //     trigger: 'change'
        //   }
        // ],
        ratio: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('m.Shop_Created_shop_profit_allocation')
          }
        ],
        address: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('m.Please_enter_address')
          }
        ],
        addressMap: [
          {
            required: true,
            trigger: 'blur',
            message: this.$t('m.Please_select_location_pin')
          }
        ]
      },
      timeList: [
        {
          stage: 1,
          name: this.$t('m.Week_Mon'),
          names: '24 ' + this.$t('m.hour4'),
          check: false,
          check2: false,
          allDay: false,
          rangeTime1: '',
          rangeTime2: '',
          rangeTime3: '',
          rangeTime4: '',
          value: 1,
          disabledTime: false
        },
        {
          stage: 1,
          name: this.$t('m.Week_Tue'),
          names: '24 ' + this.$t('m.hour4'),
          check: false,
          check2: false,
          allDay: false,
          rangeTime1: '',
          rangeTime2: '',
          rangeTime3: '',
          rangeTime4: '',
          value: 2,
          disabledTime: false
        },
        {
          stage: 1,
          name: this.$t('m.Week_Wed'),
          names: '24 ' + this.$t('m.hour4'),
          check: false,
          check2: false,
          allDay: false,
          rangeTime1: '',
          rangeTime2: '',
          rangeTime3: '',
          rangeTime4: '',
          value: 3,
          disabledTime: false
        },
        {
          stage: 1,
          name: this.$t('m.Week_Thu'),
          names: '24 ' + this.$t('m.hour4'),
          check: false,
          check2: false,
          allDay: false,
          rangeTime1: '',
          rangeTime2: '',
          rangeTime3: '',
          rangeTime4: '',
          value: 4,
          disabledTime: false
        },
        {
          stage: 1,
          name: this.$t('m.Week_Fri'),
          names: '24 ' + this.$t('m.hour4'),
          check: false,
          check2: false,
          allDay: false,
          rangeTime1: '',
          rangeTime2: '',
          rangeTime3: '',
          rangeTime4: '',
          value: 5,
          disabledTime: false
        },
        {
          stage: 1,
          name: this.$t('m.Week_Sat'),
          names: '24 ' + this.$t('m.hour4'),
          check: false,
          check2: false,
          allDay: false,
          rangeTime1: '',
          rangeTime2: '',
          rangeTime3: '',
          rangeTime4: '',
          value: 6,
          disabledTime: false
        },
        {
          stage: 1,
          name: this.$t('m.Week_Sun'),
          names: '24 ' + this.$t('m.hour4'),
          check: false,
          check2: false,
          allDay: false,
          rangeTime1: '',
          rangeTime2: '',
          rangeTime3: '',
          rangeTime4: '',
          value: 0,
          disabledTime: false
        }
      ],
      countryCode: '', //国家码
      fileList1: [], //logo
      fileList2: [], //照片
      industrys: '', //行业
      billings: '', //计费规则
      deposits: '', //预付款规则
      agents: [], //代理
      stations: [], // 机柜
      editStations: [], //回显机柜
      googleMaps: '', //地图
      loading: false,
      restaurants: [], //搜索结果
      timeout: null,
      ruleForms: {
        email: ''
      },
      rules: {
        email: [
          {
            required: true,
            message: this.$t('m.Enter_invitation_email'),
            trigger: 'blur'
          },
          {
            pattern: this.$reg.email.val,
            message: this.$t('m.EnterCorrectEmail'),
            trigger: 'blur'
          }
        ]
      },
      elRadio: 1, // 邀请类型
      inviteDialog: false, //邀请链接弹窗
      linkType: 2, //邀请链接弹窗类型
      inviteData: '', //邀请链接及时间
      shopId: '', //创建生成的商家id
      userType: this.getUserType(), //用户身份
      editAuth: this.permissionsId(20), //商家编辑

      checkedCities: [],
      cities: [
        { value: 1, label: this.$t('m.Week_Mon') },
        { value: 2, label: this.$t('m.Week_Tue') },
        { value: 3, label: this.$t('m.Week_Wed') },
        { value: 4, label: this.$t('m.Week_Thu') },
        { value: 5, label: this.$t('m.Week_Fri') },
        { value: 6, label: this.$t('m.Week_Sat') },
        { value: 0, label: this.$t('m.Week_Sun') }
      ],
      timeList1: {
        stage: 1,
        names: '24 ' + this.$t('m.hour4'),
        check: false,
        check2: false,
        allDay: false,
        rangeTime1: '',
        rangeTime2: '',
        rangeTime3: '',
        rangeTime4: '',
        disabledTime: false
      }
    }
  },

  created () {
    if (!this.editAuth) {
      return
    }
    this.countryCode = countries
    this.getIndustrys()
    this.getAgents()
    if (this.$route.query.id) {
      this.$api.shop.shopEditDetail(this.$route.query.id).then(res => {
        let times = JSON.parse(res.data.openTime).businessHours
        times.forEach(item => {
          const index = this.timeList.findIndex(i => i.value === item.value)
          if (
            item.rangeTime1 != null &&
            item.rangeTime1 != '' &&
            item.rangeTime1.length > 0
          ) {
            this.timeList[index].stage = 1
          }
          if (
            item.rangeTime2 != null &&
            item.rangeTime2 != '' &&
            item.rangeTime2.length > 0
          ) {
            this.timeList[index].stage = 2
          }
          if (
            item.rangeTime3 != null &&
            item.rangeTime3 != '' &&
            item.rangeTime3.length > 0
          ) {
            this.timeList[index].stage = 3
          }
          if (
            item.rangeTime4 != null &&
            item.rangeTime4 != '' &&
            item.rangeTime4.length > 0
          ) {
            this.timeList[index].stage = 4
          }
          if (index > -1) {
            this.timeList[index].check2 = item.check
            this.timeList[index].allDay = item.allDay
            this.timeList[index].rangeTime1 =
              item.rangeTime1.length == 0 ? '' : item.rangeTime1
            this.timeList[index].rangeTime2 =
              item.rangeTime2.length == 0 ? '' : item.rangeTime2
            this.timeList[index].rangeTime3 =
              item.rangeTime3.length == 0 ? '' : item.rangeTime3
            this.timeList[index].rangeTime4 =
              item.rangeTime4.length == 0 ? '' : item.rangeTime4
          }
          if (item.allDay == true) {
            this.timeList[index].disabledTime = true
          } else {
            this.timeList[index].disabledTime = false
          }
          if (this.timeList[index].check2 && res.data.openTimeType == 1) {
            this.checkedCities.push(this.timeList[index].value)
            this.timeList1 = {
              stage: this.timeList[index].stage,
              names: '24 ' + this.$t('m.hour4'),
              check: this.timeList[index].check,
              check2: this.timeList[index].check2,
              allDay: this.timeList[index].allDay,
              rangeTime1: this.timeList[index].rangeTime1,
              rangeTime2: this.timeList[index].rangeTime2,
              rangeTime3: this.timeList[index].rangeTime3,
              rangeTime4: this.timeList[index].rangeTime4,
              disabledTime: this.timeList[index].disabledTime
            }
            this.timeList = this.$options.data.call(this).timeList
          }
        })
        if (res.data.images) {
          res.data.images
            .split(',')
            .forEach(item => [this.fileList2.push({ url: item })])
        }
        this.params = {
          id: this.$route.query.id,
          agentId: res.data.agentId,
          shopName: res.data.branchName, //	网点名称 .
          address: res.data.address, //详细地址信息(手动输入)
          addressMap: res.data.addressMap, //详细地址信息(地图)
          billingId: res.data.billingId,
          branchProfile: res.data.branchProfile,
          depositId: res.data.depositId, //	押金规则id
          scanList: [], //机柜扫码标号 .
          phone: res.data.phone, //电话 .
          lat: res.data.lat, //	纬度
          lng: res.data.lng, //	经度
          logo: res.data.logo, //logo图片地址
          openTime: JSON.parse(res.data.openTime), //营业时间
          openTimeType: res.data.openTimeType,
          principal: res.data.principal, //负责人
          ratio: res.data.ratio, //网点分成比例 .
          images: res.data.images, //网点形象照片地址
          industryId: res.data.industryId, //行业id
          code: res.data.code
        }
        this.editStations = res.data.list
        this.getCabinets()
      })
    } else {
      this.getCabinets()
    }
    const maplang = 'en-US'
    const script = document.createElement('script')
    script.src = `https://maps.googleapis.com/maps/api/js?key=AIzaSyC2e07mMyqmU_64jJVJcx7Ti-uACnCT_8c&libraries=visualization&language=${maplang}`
    script.async = true
    script.defer = true
    document.head.appendChild(script)
    script.onload = () => {
      this.initializeMap()
    }
  },
  mounted () {},
  methods: {
    // 地图搜索
    searchMap () {
      var self = this
      var geocoder = new google.maps.Geocoder()

      geocoder.geocode(
        { address: self.params.addressMap },

        function geoResults (results, status) {
          // 状态为Ok说明有结果
          if (status == google.maps.GeocoderStatus.OK) {
            var list = results

            if (list.length == 1) {
              self.params.addressMap = list[0].formatted_address // 地图上标记的

              self.params.lat = list[0].geometry.location.lat() // 经纬度
              self.params.lng = list[0].geometry.location.lng()

              self.marker.setPosition(
                new google.maps.LatLng(self.params.lat, self.params.lng)
              )

              self.googleMaps.setCenter(self.marker.getPosition())
              return
            } else if (list.length === '0') {
              self.$message({
                type: 'error',
                message: status
              }) // 弹框
              return
            }
          } else {
          }
        }
      )
    },
    // 初始化地图
    initializeMap () {
      var self = this
      setTimeout(() => {
        if (!self.googleMaps) {
          self.googleMaps = new google.maps.Map(
            document.getElementById('googleMap'),
            {
              // 创建地图
              center: new google.maps.LatLng(self.params.lat, self.params.lng),
              zoom: 14,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            }
          )

          self.marker = new google.maps.Marker({
            // 添加标记
            map: self.googleMaps,
            draggable: true,
            position: new google.maps.LatLng(self.params.lat, self.params.lng)
          })

          google.maps.event.addListener(
            self.marker,
            'dragend',
            function (MouseEvent) {
              // console.log(MouseEvent, 'MouseEvent')
              var geocoder = new google.maps.Geocoder()
              var latg = MouseEvent.latLng.toString()

              self.params.lat = latg.split(',')[0].substr(1) // 移动图标得到的位置
              self.params.lng = latg.split(',')[1]

              // console.log(self.params.lat, self.params.lng, '移动的经纬度')

              self.params.lng = self.params.lng.split(')')[0]
              self.geocodeLatLng(MouseEvent.latLng, geocoder)
            }
          )
        } else {
          self.marker.setPosition(
            // 坐标
            new google.maps.LatLng(self.params.lat, self.params.lng)
          )
          self.googleMaps.setCenter(self.marker.getPosition()) // 返回类型GLatLng 返回地图中心点的地图坐标.
        }
      }, 1500)
    },
    // 经纬度转地址
    geocodeLatLng (latlng, geocoder) {
      var self = this
      geocoder.geocode(
        {
          location: latlng
        },
        function (results, status) {
          if (status === 'OK') {
            // console.log(results[0].formatted_address, '移动地址')
            self.params.addressMap = results[0].formatted_address // 地图上标记的
          }
        }
      )
    },

    renderContent (h, option) {
      // console.log(option)
      return (
        <span>
          <span
            class='label'
            style='font-size: 12px !important;line-height: 14px !important;'
          >
            {option.label}
            <span style='padding:0 2px;'>·</span>
            {option.deviceCount + ' '}
            {this.$t('m.Station_List_placeholder_Device_info')}
          </span>
          <br />
          <span
            class='name'
            style='font-size: 12px !important;line-height: 14px !important; color:#888888;'
          >
            {option.isScreen == 0
              ? this.$t('m.Without_screen')
              : this.$t('m.Advertising_screen')}
          </span>
        </span>
      )
    },

    //获取行业列表
    getIndustrys () {
      this.$api.common.getIndustriesList().then(res => {
        if (this.$ok(res)) {
          let array = res.data.map(item => {
            item.industryName = this.$format.langFormat(
              item.industryName,
              this.$cache.getLang()
            )
            item.description = this.$format.langFormat(
              item.description,
              this.$cache.getLang()
            )
            return item
          })
          this.industrys = array
        }
      })
    },

    //获取代理商列表
    getAgents () {
      this.$api.shop.getAgentsTree().then(res => {
        if (this.$ok(res)) {
          if (this.userType == 1) {
            this.agents = [
              {
                id: 0,
                name: this.$t('m.Platform'),
                parentId: null,
                children: res.data
              }
            ]
          } else {
            this.agents = res.data
            if (this.getAgentLevel() == 2) {
              this.params.agentId = res.data[0].id
            }
          }
        }
      })
    },
    //获取机柜
    getCabinets () {
      let params = {
        type: 1,
        branchId: this.$route.query.id ? this.$route.query.id : ''
      }
      this.$api.shop.getCabinetsList(params).then(res => {
        if (this.$ok(res)) {
          res.data.forEach(item => {
            this.stations.push({
              label: item.cabinetNo,
              key: item.cabinetNo,
              deviceCount: item.deviceCount,
              isScreen: item.isScreen
            })
          })
          this.editStations.forEach(item => {
            this.stations.push({
              label: item.cabinetNo,
              key: item.cabinetNo,
              deviceCount: item.deviceCount,
              isScreen: item.isScreen
            })
            this.params.scanList.push(item.cabinetNo)
          })
        }
      })
    },
    //网点图片logo
    getLogo (res, file) {
      // console.log(file.response.data.value)
      this.params.logo = file.response.data.value
    },
    //删除网点logo
    deleteLogo () {
      this.params.logo = ''
      this.fileList1 = []
    },
    //门面照
    getPicture (res, file) {
      this.fileList2.push({
        url: file.response.data.value
      })
    },
    //上传前限制
    beforeUpload (file) {
      const isJPG =
        file.type == 'image/jpeg' ||
        file.type == 'image/png' ||
        file.type == 'image/jpg'
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isJPG) {
        this.$message.error(this.$t('m.Upload_image_type'))
        return false
      }
      if (!isLt1M) {
        this.$message.error(this.$t('m.Upload_image_size'))
        return false
      }
      return isJPG && isLt1M
    },
    //删除网点图片
    deletePicture (index) {
      this.fileList2.splice(index, 1)
    },

    //手机号输入限制
    changePhone (val) {
      this.params.phone = this.$check.onlyNum(val)
    },
    //分成比例输入限制
    changeRatio (val) {
      this.params.ratio = this.$check.onlyNum(val)
      if (this.params.ratio > 100) {
        this.params.ratio = 100
      }
    },
    changeCheck1 (item, index) {
      if (item.check2 == true) {
        this.changeCheck2(item, index)
      } else {
        this.timeList[index].allDay = false
        this.timeList[index].check = false
        this.timeList[index].disabledTime = false
      }
    },
    changeCheck2 (item, index) {
      if (item.allDay == true) {
        this.timeList[index].check = false
        this.timeList[index].disabledTime = true
      } else {
        this.timeList[index].check = true
        this.timeList[index].disabledTime = false
      }
    },
    // 添加营业时间
    addTime (index) {
      this.timeList[index].stage = this.timeList[index].stage + 1
    },
    // 减去时间
    reduceTime (index) {
      // console.log(this.timeList[index].stage)
      if (this.timeList[index].stage == 4) {
        this.timeList[index].rangeTime4 = ''
        this.timeList[index].stage = this.timeList[index].stage - 1
        return
      }
      if (this.timeList[index].stage == 3) {
        this.timeList[index].rangeTime3 = ''
        this.timeList[index].stage = this.timeList[index].stage - 1
        return
      }
      if (this.timeList[index].stage == 2) {
        this.timeList[index].stage = this.timeList[index].stage - 1
        this.timeList[index].rangeTime2 = ''
        return
      }
    },
    //编辑/保存
    async saveClick () {
      try {
        await Promise.all([this.$refs.params1.validate()])
        let openTimeData = []
        if (this.params.openTimeType == 1) {
          let list1 = JSON.parse(JSON.stringify(this.timeList))
          list1.forEach(item => {
            openTimeData.push({
              value: item.value,
              check: this.checkedCities.includes(item.value),
              allDay: this.checkedCities.includes(item.value)
                ? this.timeList1.allDay
                : false,
              rangeTime1:
                this.timeList1.rangeTime1 &&
                this.checkedCities.includes(item.value)
                  ? this.timeList1.rangeTime1
                  : [],
              rangeTime2:
                this.timeList1.rangeTime2 &&
                this.checkedCities.includes(item.value)
                  ? this.timeList1.rangeTime2
                  : [],
              rangeTime3:
                this.timeList1.rangeTime3 &&
                this.checkedCities.includes(item.value)
                  ? this.timeList1.rangeTime3
                  : [],
              rangeTime4:
                this.timeList1.rangeTime4 &&
                this.checkedCities.includes(item.value)
                  ? this.timeList1.rangeTime4
                  : []
            })
          })
          // console.log(openTimeData);
        } else {
          this.timeList.forEach(item => {
            openTimeData.push({
              value: item.value,
              check: item.check2,
              allDay: item.allDay,
              rangeTime1: item.rangeTime1 ? item.rangeTime1 : [],
              rangeTime2: item.rangeTime2 ? item.rangeTime2 : [],
              rangeTime3: item.rangeTime3 ? item.rangeTime3 : [],
              rangeTime4: item.rangeTime4 ? item.rangeTime4 : []
            })
          })
          // console.log(openTimeData);
        }
        // console.log(openTimeData);
        this.params.openTime.businessHours = openTimeData
        this.params.images = this.fileList2
          .map(item => {
            return item.url
          })
          .join(',')
        let params = { ...this.params }
        if (this.$route.query.id) {
          params.openTime = JSON.stringify(params.openTime)
          this.$api.shop.editShop(params).then(res => {
            if (this.$ok(res)) {
              this.$message.success(res.message)
              this.$router.go(-1)
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          params.openTime.check = false
          params.openTime = JSON.stringify(params.openTime)
          this.$api.shop.addShop(params).then(res => {
            if (this.$ok(res)) {
              this.$message.success(res.message)
              this.linkType = 2
              this.shopId = res.data.id
              this.inviteDialog = true
            } else {
              this.$message.error(res.message)
            }
          })
        }
      } catch (error) {
        // 验证失败
        // console.log('error submit !')
        return
      }
    },

    //邀请店主
    inviteShopkeeper () {
      this.$api.branch.inviteShopkeeper(this.shopId).then(res => {
        if (this.$ok(res)) {
          this.inviteData = res.data
          this.elRadio = 1
          this.linkType = 1
          this.ruleForms.email = ''
        } else {
          this.$message.error(res.message)
        }
      })
    },

    //邀请店主-邮件
    inviteShopemail () {
      this.$refs.ruleForms.validate(valid => {
        if (valid) {
          this.$api.branch
            .inviteShopemail(this.shopId, this.ruleForms)
            .then(res => {
              if (this.$ok(res)) {
                this.$message.success(res.message)
                this.backPage()
              } else {
                this.$message.error(res.message)
              }
            })
        }
      })
    },

    //返回上一页
    backPage () {
      this.remPageNum()
      this.$router.go(-1)
    },

    //确认邀请
    submitInvite () {
      if (this.linkType == 2) {
        this.inviteShopkeeper()
      } else {
        this.elRadio == 1 ? this.backPage() : this.inviteShopemail()
      }
    },

    // 选择品牌、代理
    handleChange (value) {
      // console.log(value)
      // console.log(this.params.agentId)
    },

    // 选择24 / 自定义时间
    changeCheck () {
      if (this.timeList1.allDay == true) {
        this.timeList1.check = false
        this.timeList1.disabledTime = true
      } else {
        this.timeList1.check = true
        this.timeList1.disabledTime = false
      }
    },

    reduceTime1 () {
      if (this.timeList1.stage == 4) {
        this.timeList1.rangeTime4 = ''
        this.timeList1.stage = this.timeList1.stage - 1
        return
      }
      if (this.timeList1.stage == 3) {
        this.timeList1.rangeTime3 = ''
        this.timeList1.stage = this.timeList1.stage - 1
        return
      }
      if (this.timeList1.stage == 2) {
        this.timeList1.stage = this.timeList1.stage - 1
        this.timeList1.rangeTime2 = ''
        return
      }
    },

    addTime1 () {
      this.timeList1.stage = this.timeList1.stage + 1
    }
  }
}
</script>
<style lang="scss" scoped>
.page-header,
.container {
  min-width: 1360px !important;
}
.tiem_el_checkbox {
  ::v-deep .el-checkbox {
    margin-bottom: 12px;
  }
}
.shop_time {
  border-bottom: 1px solid #f0f0f7;
  .time_check {
    display: flex;
    padding: 18px 0;
    .shop_week {
      display: flex;
      align-items: center;
      .week_name {
        font-size: 14px;
        font-weight: 500;
        text-align: left;
        color: #39404d;
        line-height: 16px;
        margin-right: 12px;
      }
    }
  }
  .shop_div2 {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    padding: 16px 0;
    // width: 392px;
    .shop_plus {
      width: 180px;
      border: 1px solid #d2d8e2;
      border-radius: 19px;
      text-align: center;
      line-height: 34px;
      height: 34px;
      font-size: 19px;
      margin-bottom: 4px;
      cursor: pointer;
    }
    .shop_plus1 {
      opacity: 0.4;
      cursor: not-allowed;
    }
    .el-icon-minus:before {
      color: #eb2300;
    }
    .el-icon-plus:before {
      color: #646b80;
    }
    .shop_icon {
      width: 86px;
      height: 34px;
      border-radius: 19px;
    }
    .shop_icon2 {
      margin-left: 4px;
    }
    .el-input__inner {
      width: 180px;
      height: 36px !important;
      line-height: 36px !important;
    }
    .el-date-editor {
      width: 180px;
      height: 36px;
      border: 1px solid #d2d8e2;
      border-radius: 19px;
      margin-right: 16px;
      margin-bottom: 4px;
    }
    .el-range-input {
      font-size: 12px;
    }
    .is-disabled {
      opacity: 0.4;
    }
    ::v-deep .el-date-editor .el-range-separator {
      line-height: 28px !important;
      color: #646b80;
      display: flex !important;
      justify-content: center !important;
      align-items: center !important;
    }
    ::v-deep .el-date-editor .el-range-input {
      font-size: 12px !important;
    }
  }
}
.detail_left_div2 {
  ::v-deep .el-input__inner {
    padding-left: 36px !important;
  }
}
</style>
